package com.sneakxy.mybase4j.platform.controller;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.sneakxy.mybase4j.base.bean.ValidAdd;
import com.sneakxy.mybase4j.base.bean.ValidEdit;
import com.sneakxy.mybase4j.base.controller.BaseController;
import com.sneakxy.mybase4j.platform.beans.Permission;
import com.sneakxy.mybase4j.platform.beans.Role;
import com.sneakxy.mybase4j.platform.beans.RolePerm;
import com.sneakxy.mybase4j.platform.service.IAccountRoleService;
import com.sneakxy.mybase4j.platform.service.IPermissionService;
import com.sneakxy.mybase4j.platform.service.IRolePermService;
import com.sneakxy.mybase4j.platform.service.IRoleService;
import com.sneakxy.mybase4j.util.BeanHelper;
import com.sneakxy.mybase4j.util.DataGrid;
import com.sneakxy.mybase4j.util.PageSearch;
import com.sneakxy.mybase4j.util.Response;

/**
 * 角色管理
 * @author 潜行的青衣
 * @see
 */
@RestController
@RequestMapping("/api/role/")
public class RoleController extends BaseController {

	@Resource
	private IRoleService roleService;
	
	@Resource
	private IPermissionService permissionService;
	
	@Resource
	private IRolePermService rolePermService;
	
	@Resource
	private IAccountRoleService accountRoleService;
	
	@RequiresPermissions("sys:role:manager")
	@RequestMapping("datagrid")
	public DataGrid<Role> datagrid(PageSearch search) {
		if(StringUtils.isBlank(search.getSortName())) {
			search.setSortName("createtime");
		}
		return new DataGrid<Role>(roleService.findBySearch(search.getSearchText(), search.toPageable()));
	}
	
	@RequiresPermissions("sys:role:manager:add")
	@RequestMapping("add")
	public Response add(@Validated(ValidAdd.class) Role role, BindingResult result) {
		if(result.hasErrors()) {
			return this.getFieldErrorsResponse(result);
		}
		
		if(!this.validate(role.getId())) {
			return new Response(false, 1);
		}
		
		//去空格
		BeanHelper.trimToEmpty(role);
		role.setNew(true);
		role.setSort(0);
		
		role = this.roleService.save(role);
		return new Response(true, role);
	}
	
	@RequiresPermissions("sys:role:manager:add")
	@RequestMapping("validate")
	public Boolean validate(String id) {
		Role old = this.roleService.findOne(StringUtils.trimToEmpty(id));
		return old == null;
	}
	
	@RequiresPermissions("sys:role:manager:edit")
	@RequestMapping("edit")
	public Response edit(@Validated(ValidEdit.class) Role role, BindingResult result) {
		if(result.hasErrors()) {
			return this.getFieldErrorsResponse(result);
		}
		
		Role old = this.roleService.findOne(role.getId());
		//去空格
		BeanHelper.trimToEmpty(role);
		role.setNew(false);
		role.setSort(0);
		role.setCreatetime(old.getCreatetime());
		
		role = this.roleService.save(role);
		return new Response(true, role);
	}
	
	@RequiresPermissions("sys:role:manager:remove")
	@RequestMapping("remove")
	public Response remove(String[] ids) {
		if(ids != null) {
			for(String id:ids) {
				this.rolePermService.deleteByRoleId(id);
				this.accountRoleService.deleteByRoleId(id);
				this.roleService.delete(id);
			}
		}
		return new Response(true);
	}
	
	@RequiresPermissions("sys:role:manager:perm")
	@RequestMapping("tree")
	public Response tree(String id) {
		Map<String, Object> result = new LinkedHashMap<String, Object>();
		List<Permission> list = this.permissionService.findAllByParentId(true);
		result.put("id", "root");
		result.put("i18n", "sys.role.manager.perm");
		result.put("open", true);
		result.put("nocheck", true);
		result.put("children", list);
		List<String> perms = rolePermService.findPermissions(StringUtils.trimToEmpty(id));
		result.put("perms", perms);
		return new Response(result);
	}
	
	@RequiresPermissions("sys:role:manager:perm")
	@RequestMapping("perm")
	public Response perm(String id, String[] permIds) {
		String roleId = StringUtils.trimToEmpty(id);
		Role role = this.roleService.findOne(roleId);
		if(role != null) {
			//删除已经分配权限
			this.rolePermService.deleteByRoleId(roleId);
			
			//重新分配权限
			if(permIds != null) {
				List<RolePerm> rps = new ArrayList<RolePerm>();
				for(String permId : permIds) {
					rps.add(new RolePerm(roleId, permId));
				}
				this.rolePermService.save(rps);
			}
			return new Response(true);
		}
		return new Response(false);
	}
	
}
